package com.hmall.gateway.filters;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义有参的GatewayFilter过滤器
 */
@Component
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> {
    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter(new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //读取参数
                System.out.println("a="+config.getA());
                System.out.println("b="+config.getB());
                System.out.println("c="+config.getC());
                System.out.println("Gateway Filter running! ");
                return chain.filter(exchange);
            }
        },2);
    }

    /**
     * 自定义配置属性，成员变量名称很重要，下面会用到
     */
    @Data
    public static class Config{
        private String a;
        private String b;
        private String c;
    }
    /**
     * 将变量名称依次返回，顺序很重要，将来读取参数时需要按顺序获
     * @return
     */
     @Override
     public List<String> shortcutFieldOrder() {
        return List.of("a", "b", "c");
    }
    /**
     * 将Config字节码传递给父类，父类负责帮我们读取yaml配置
     */
    public PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }
}
